<?php

namespace App\Services\CloseUnpaidProductOrder;

use Carbon\Carbon;
use App\Models\Order;
use App\Models\SeckillProduct;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class CloseUnpaidProductOrder
{
	protected $order;
	
	public function __construct(Order $order)
	{
		$this->order = $order;
	}
	
	protected function close()
	{
		DB::transaction(function () {
			
			$this->order->update(['closed_at' => Carbon::now()]);
			$this->order->items->each(function ($item) {
				$item->sku->increaseStock($item->amount);
				if($this->order->sid){
					Redis::decrBy(SeckillProduct::userSeckillCount($this->order->user_id,$this->order->sid),$item->amount);
				}
			});
		});
	}
	
	protected function canBeClosed()
	{
		if ($this->order->isClosed()) return false;
		if ($this->order->isPaid()) return false;
		return true;
	}
	
	public function closeByUser()
	{
		if (! $this->canBeClosed()) return;
		
		$this->close();
	}
	
	public function closeByJob()
	{
		if (! $this->canBeClosed()) return;
		
		$this->close();
	}
}
